using Abc.Core;

using Furion;

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

using System.Linq;

//https://www.cnblogs.com/hulizhong/p/10779687.html

namespace Abc.Web.Core
{
    /// <summary>
    /// Admin 权限过滤器
    /// UseAuthorization();//授权
    /// </summary>
    public class PermissionFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 权限类型，默认HtAdmin
        /// </summary>
        public string PermissionType { get; set; } = "HtAdmin";

        public PermissionFilterAttribute()
        {

        }
        public PermissionFilterAttribute(string permissionType)
        {
            this.PermissionType = permissionType;
        }
        public override async void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //判断请求的控制器有没有加上NoPermissionRequiredAttribute或AllowAnonymousAttribute（不需要权限）
            var controllerAttributes = filterContext.Controller.GetCustomAttributes();
            if (controllerAttributes.Any(a => a.GetType().Equals(typeof(NoPermissionRequiredAttribute)) || a.GetType().Equals(typeof(AllowAnonymousAttribute))))
            {
                return;
            }
            //判断请求的方法有没有加上NoPermissionRequiredAttribute或AllowAnonymousAttribute（不需要权限）
            var controllerActionAttributes = filterContext.ActionDescriptor.GetCustomAttributes();
            if (controllerActionAttributes.Any(a => a.GetType().Equals(typeof(NoPermissionRequiredAttribute)) || a.GetType().Equals(typeof(AllowAnonymousAttribute))))
            {
                return;
            }
            var filtercontextinfo = new FilterContextInfo(filterContext);
            if (filtercontextinfo.UserId <= 0)
            {
                NoAuth(filterContext);
            }
            else
            {
                var cacheService = App.GetService<ICacheService>();
                var isHasAuth = await cacheService.HasAuthorize(this.PermissionType, filtercontextinfo.ControllerName, filtercontextinfo.ActionName, filtercontextinfo.UserId);
                if (!isHasAuth)
                {
                    NoAuth(filterContext);
                }
            }

            base.OnActionExecuting(filterContext);
        }

        private void NoAuth(ActionExecutingContext filterContext)
        {
            //没得权限
            filterContext.Result = new RedirectResult("/HtAdmin/Account/Login");


            //var content = new ContentResult();
            //content.Content = "没有权限";
            //content.StatusCode = 403;//403(Forbidden)：禁止。服务器拒绝接受请求。
            //filterContext.Result = content;
        }

        /// <summary>
        /// 不验证权限
        /// </summary>
        public class NoPermissionRequiredAttribute : ActionFilterAttribute
        {
        }
    }
}